package com.jar.exercise.网络编程.TCP连接.客服端和服务端;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 例子：复制文件，图片不能用字符流
 * 客户端发送文件到服务器，服务器下载到本地，并返回发送成功到客户端
 * 难点：中间有一个结束标记，socket.shutdownOutput();
 */
class Server2 {

	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(12000);
		Socket socket = serverSocket.accept();
		InputStream fis = socket.getInputStream();
		FileOutputStream fos = new FileOutputStream(new File("d:/ss.png"));
		byte[] b = new byte[1024];
		int len;
		while ((len = fis.read(b)) != -1) {
			fos.write(b, 0, len);
		}
		OutputStream out = socket.getOutputStream();
		out.write("我看到了你的图片很好".getBytes());
		out.close();
		fos.close();
		socket.close();
		serverSocket.close();
	}
}

class Client2 {
	public static void main(String[] args) throws IOException {
		//创建连接
		Socket socket = new Socket("192.168.234.1", 12000);
		FileInputStream fis = new FileInputStream(new File("d:/person_1.png"));
		OutputStream outputStream = socket.getOutputStream();
		byte[] b = new byte[1024];
		int len;
		while ((len = fis.read(b)) != -1) {
			outputStream.write(b, 0, len);
		}
		socket.shutdownOutput();
		ByteArrayOutputStream bais = new ByteArrayOutputStream();
		byte[] bb = new byte[1024];
		InputStream inputStream = socket.getInputStream();
		int lens;
		if ((lens = inputStream.read(bb)) != -1) {
			bais.write(bb, 0, lens);
		}
		System.out.println(bais.toString());
		fis.close();
		socket.close();
	}

}
